#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import shutil
import string
import re
import xml.etree.ElementTree as etree
sys.path.append("E:/SVN/SGSDK/SGTools/SGAutoPack/SGPythonUtils")
import ConfigFileEdit

namespace = "http://schemas.android.com/apk/res/android"

baidulib = "E:/SVN/SGSDK/SGAna/SGBAIDU/SGBAIDU"
dksdk_channel = "14076"
gamedir = "E:/gamecopy"
backuplib = "E:/SVN/SGSDK/SGTools/SGAutoPack/autopack_v4_ppl2/temp"
fourlib = "E:/SVN/SGSDK/SGSMS/FOUR"

#检查资源相关的目录是否存在
def checkDirExist():
	if(False == os.path.exists(baidulib)):
		print( baidulib + " is not exist")
		raise( baidulib + " is not exist")

#copy文件
def copyFileSafety(backupfile,desfile):
	if( True == os.path.exists(backupfile) ):
		if( True == os.path.exists(desfile) ):
			os.remove(desfile)
		shutil.copyfile(backupfile,desfile)

#delete文件
def deleteFileSafety(filepath):
	if( True == os.path.exists(filepath) ):
			os.remove(filepath)

#读取xml获得根节点
def read_xml(xml_file):
	tree = etree.parse(xml_file)
	return tree

def parse_attribute_name(attribute_name):
	ns = {
			'android:value' : '{%s}value' % namespace,
			'android:name' : '{%s}name' % namespace
		}
	return ns[attribute_name]

def run(src_xml, save_file):
	if( False == os.path.exists(src_xml) ):
		raise Exception(src_xml + "文件不存在，请检查!")
	if( False == os.path.exists(save_file) ):
		raise Exception(save_file + "文件不存在，请检查!")

	etree.register_namespace('android', namespace)
	
	tree = read_xml(src_xml)
	root = tree.getroot()

	for elem in root.findall('application/meta-data'):
		att = elem.get("{%s}name" % namespace)
		if att == "dksdk_channel":
			elem.set('{%s}value'% namespace, dksdk_channel)

	tree.write(save_file, "utf-8")

	
	
#调整资源
def channelCustomOperBegin():
	print("begin , this is baidu !")
	checkDirExist()

	#修改dksdk_channel
	fileSrcName = baidulib + "/AndroidManifest.xml"
	backupFile = baidulib + "/AndroidManifest.xml_channnelbak"
	copyFileSafety(fileSrcName,backupFile)
	run(fileSrcName,fileSrcName)
	
#	#修改运营商
#	#其实如果是mm三网切jd，Manifest文件里的Main也要删掉(目前没做处理)
#	projectfile = fourlib + "/project.properties"
#	liblist = [
#		'../../SGUtil/SGSDKUtils_Library',
#		'../SmsLib/sms_lib_ayx_4.2.0',
#		'../SmsLib/sms_lib_lt_4.0.2',
#		'../SmsLib/sms_lib_jd_26005_release'
#	]
#	ConfigFileEdit.setProjectRefLib(projectfile,liblist)
	
#	#运营商配置
#	baiduPayTypeConfig = backuplib + "/baidu/baidu_payTypeConfig.xml"
#	gamePayTypeConfig = gamedir + "/assets/soulgame/payTypeConfig.xml"
#	copyFileSafety(baiduPayTypeConfig,gamePayTypeConfig)
	
	#百度支付需要用到计费点文件
	backup_baiduparamsfile = backuplib + "/baidu/sg_sdk_params.info"
	game_baiduparamsfile = gamedir + "/assets/sg_sdk_params.info"
	copyFileSafety(backup_baiduparamsfile,game_baiduparamsfile)

	#处理百度闪屏顺序问题
	baiduAppActivity = backuplib + "/baidu/baidu_AppActivity.java"
	gameAppActivity = gamedir + "/src/org/cocos2dx/lua/AppActivity.java"
	copyFileSafety(baiduAppActivity,gameAppActivity)



#恢复资源
def channelCustomOperEnd():
	print("end , this is baidu !")
	checkDirExist()
	
#	#还原运营商配置
#	backupFourProjectFile = backuplib + "/four_project.properties"
#	fourProjectFile = fourlib + "/project.properties"
#	copyFileSafety(backupFourProjectFile,fourProjectFile)

	fileSrcName = baidulib + "/AndroidManifest.xml"
	backupFile = baidulib + "/AndroidManifest.xml_channnelbak"
	copyFileSafety(backupFile,fileSrcName)
	deleteFileSafety(backupFile)

	#sg_sdk_params.info、AppActivity.java、payTypeConfig.xml因为操作的是copy目录，所以不用执行恢复操作了

if __name__=="__main__":
	if(sys.argv[1] == "begin"):
		channelCustomOperBegin()
	elif(sys.argv[1] == "end"):
		channelCustomOperEnd()
	else:
		raise("call channel custom operation must with param begin or end!")

#	channelCustomOperBegin()
#	channelCustomOperEnd()
